package com.hina.rec.common.handler;

import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.util.BooleanUtils;
import cn.idev.excel.write.handler.CellWriteHandler;
import cn.idev.excel.write.handler.context.CellWriteHandlerContext;
import cn.idev.excel.write.metadata.holder.WriteSheetHolder;
import cn.idev.excel.write.metadata.style.WriteCellStyle;
import cn.idev.excel.write.metadata.style.WriteFont;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

/**
 * fastexcel自定义单元格样式
 *
 * @author gengkeke
 * @since 2025/4/24
 */
@Slf4j
public class CustomCellStyleWriteHandler implements CellWriteHandler {

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        // 内容单元格的样式
        if (BooleanUtils.isNotTrue(context.getHead())) {
            WriteCellData<?> cellData = context.getFirstCellData();
            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
            WriteFont writeFont = new WriteFont();
            writeFont.setFontName("微软雅黑");
            writeFont.setFontHeightInPoints((short) 11);
            writeCellStyle.setWriteFont(writeFont);
        }
        // 表头的样式
        if (BooleanUtils.isTrue(context.getHead())) {
            WriteCellData<?> cellData = context.getFirstCellData();
            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
            writeCellStyle.setWrapped(false);
            writeCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            writeCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            writeCellStyle.setLocked(true);
            writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            writeCellStyle.setFillForegroundColor(IndexedColors.ROYAL_BLUE.getIndex());
            writeCellStyle.setBorderTop(BorderStyle.NONE);
            writeCellStyle.setBorderBottom(BorderStyle.NONE);
            writeCellStyle.setBorderLeft(BorderStyle.NONE);
            writeCellStyle.setBorderRight(BorderStyle.NONE);
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontName("微软雅黑");
            headWriteFont.setFontHeightInPoints((short) 11);
            headWriteFont.setBold(false);
            headWriteFont.setColor(IndexedColors.WHITE.getIndex());
            writeCellStyle.setWriteFont(headWriteFont);
        }
        //默认列宽20
        WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
        if (context.getRelativeRowIndex() != null && (context.getHead() || context.getRelativeRowIndex() == 0)) {
            Sheet sheet = writeSheetHolder.getSheet();
            int columnIndex = context.getCell().getColumnIndex();
            if (sheet.getColumnWidth(columnIndex) <= 8 * 256) {
                sheet.setColumnWidth(columnIndex, 20 * 256);
            }
        }
    }

}